package org.deng.learn.basic.nio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ Author: DengLibin
 * @ Description: 传统socket服务端 bio
 *
 * 弊端:
 * 1、单线程情况下，无法处理并发连接（accept和read都是阻塞）
 * 2、使用多线程，不活跃（无数据接收和发送）的连接也会占用线程资源
 * @ DateTime:  23:35 2018/5/3 0003
 */
public class BIOServer {

    public static void  main(String[] args) throws IOException {
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        //创建socket服务,监听10101端口
        ServerSocket server = new ServerSocket(10101);
        System.out.println("服务器启动！");
        while (true) {
            //获取一个套接字连接（阻塞）
            final Socket socket = server.accept();
            System.out.println("来个一个新客户端！"+socket.getInetAddress()+":"+socket.getPort());
            // 将socket交给工作线程
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    //业务处理
                    handler(socket);
                }
            });

        }
    }
        /**
         * 读取数据
         * @param socket
         * @throws Exception
         */
        public static void handler(Socket socket){
            try {
                byte[] bytes = new byte[1024];
                InputStream inputStream = socket.getInputStream();
                while(true){
                    //读取数据（阻塞）
                    int read = inputStream.read(bytes);
                    if(read != -1){
                        System.out.println(new String(bytes, 0, read));
                        socket.getOutputStream().write("nihao".getBytes());
                    }else{
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                try {
                    System.out.println("socket关闭");
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

}
